package com.aboo.frame;

import com.aboo.domain.SysUser;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtil {

    private static final long EXPIRE_TIME = 15 * 60 * 1000;
    private static final String TOKEN_SECRET = "token123";  //密钥盐

    /**
     * 签名生成
     *
     * @param user
     * @return
     */
    public static String sign(SysUser user) {
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Map<String, Object> headerClaims = new HashMap<>(4);
            headerClaims.put("alg", "HS256");
            headerClaims.put("typ", "JWT");

            token = JWT.create().withHeader(headerClaims)
                    .withIssuer("auth0")
                    .withClaim("userName", user.getUsername())
                    .withClaim("userId", "123456")
                    .withExpiresAt(expiresAt)
                    // 使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return token;
    }


    /**
     * 签名验证
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
            System.out.println("认证通过:");
            System.out.println("issuer:" + jwt.getIssuer());
            System.out.println("userName:" + jwt.getClaim("userName").asString());
            System.out.println("userId:" + jwt.getClaim("userId").asString());
            System.out.println("过期时间:" + jwt.getExpiresAt());
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
